#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define MAX_BUFFER_SIZE 1024

// 向服务器发送消息
int send_message(int socket, const char *message) {
    ssize_t bytes_sent = write(socket, message, strlen(message));
    if (bytes_sent == -1) {
        perror("向服务器发送消息失败");
        return -1;
    }
    printf("向服务器发送消息：%s\n", message);
    return 0;
}

// 接收服务器的响应
int receive_message(int socket, char *buffer, size_t buffer_size) {
    ssize_t bytes_read = read(socket, buffer, buffer_size - 1);
    if (bytes_read == -1) {
        perror("接收服务器消息失败");
        return -1;
    } else if (bytes_read > 0) {
        buffer[bytes_read] = '\0';
        printf("从服务器接收到响应：%s\n", buffer);
    }
    return 0;
}

int main() {
    // 1. 创建套接字
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1) {
        perror("创建套接字失败");
        return -1;
    }

    // 2. 准备服务器地址结构体
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    memset(server_addr.sin_zero, 0, sizeof(server_addr.sin_zero));

    // 3. 连接服务器
    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("连接服务器失败");
        close(client_socket);
        return -1;
    }

    // 4. 使用封装的函数发送消息
    char message[MAX_BUFFER_SIZE] = "hello！";
    if (send_message(client_socket, message) == -1) {
        close(client_socket);
        return -1;
    }
    
   // 5. 使用封装的函数接收响应
    char buffer[MAX_BUFFER_SIZE];
    if (receive_message(client_socket, buffer, MAX_BUFFER_SIZE) == -1) {
        close(client_socket);
        return -1;
    }

    // 6. 关闭客户端套接字
    close(client_socket);
    return 0;
}
